<template>
  <div>
    <div class="list-main">
      <div class="flex items-center my-4">
        <SectionTitle title="流转信息" />
        <a-button
          type="link"
          size="small"
          class="ml-4"
          @click="
            openNewConditionModel(true, {
              isUpdate: false,
              record: { workItemId },
            })
          "
          >新增状态</a-button
        >
      </div>
      <div v-for="(item, index) in listRef" :key="item.originalID" class="item">
        <div class="top-info">
          <div class="title"
            >{{ item.activityName
            }}<span v-if="item.userNames" class="ml-4">({{ item.userNames }})</span></div
          >
          <div class="flex-1 ml-6" v-if="index > 0 && !item.newEntryFlag">
            <a-button type="link" size="small" @click="openChooseModal(index)">增加</a-button>
          </div>
          <div class="flex-1 ml-6" v-if="item.newEntryFlag">
            <a-button type="link" danger size="small" @click="delStateHandler(index)"
              >删除</a-button
            >
          </div>
        </div>

        <div class="item-content">
          <div
            v-for="(childrenItem, childrenIndex) in item.restoreEnrtyDetailDtoList"
            :key="childrenIndex"
            class="children-item flex items-center"
          >
            <div class="desc" :class="{ del: childrenItem.delFlag }" v-if="childrenItem.showTitle"
              >{{ childrenItem.recipients }}
              <template v-if="childrenItem.finishedDate"
                >在 {{ childrenItem.finishedDate }}</template
              >
              {{ childrenItem.showTitle }}</div
            >

            <div class="flex-1">
              <template v-if="childrenItem.delFlag">
                <a-button type="link" size="small" @click="onConfirm(index, childrenIndex)"
                  >恢复</a-button
                >
              </template>

              <template v-else>
                <a-button
                  type="link"
                  size="small"
                  @click="openConditionModelHandler(index, childrenIndex, childrenItem)"
                  >修改</a-button
                >
                <PopConfirmButton
                  v-if="index > 0"
                  title="是否确认删除?"
                  type="link"
                  danger
                  size="small"
                  @confirm="onConfirm(index, childrenIndex)"
                >
                  删除
                </PopConfirmButton>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>
    <ChooseUserModal @register="registerModel" @success="successHandler" />
    <ConditionModal @register="registerConditionModel" @success="successConditionHandler" />
    <NewConditionModal
      @register="registerNewConditionModel"
      @success="successNewConditionHandler"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, watchEffect, watch } from 'vue';
  import SectionTitle from '../SectionTitle.vue';
  import { PopConfirmButton } from '/@/components/Button';
  import ChooseUserModal from '../ChooseUserModal.vue';
  import ConditionModal from './ConditionModal.vue';
  import NewConditionModal from './NewConditionModal.vue';
  import { useModal } from '/@/components/Modal';

  const props = defineProps({
    workItemId: [Number, String],
    list: {
      type: Array as unknown as any[],
      default: () => [],
    },
  });

  const emit = defineEmits(['update:list']);

  const listRef = ref<any>([]);
  const currentIndex = ref();
  const childrenCurrentIndex = ref();

  watchEffect(() => {
    listRef.value = props.list;
  });

  watch(
    () => props.list,
    (val) => {
      listRef.value = val;
    },
  );

  const [registerModel, { openModal, closeModal }] = useModal();
  const [registerConditionModel, { openModal: openConditionModel }] = useModal();
  const [registerNewConditionModel, { openModal: openNewConditionModel }] = useModal();

  function onConfirm(index, childrenIndex) {
    listRef.value.forEach((item, idx) => {
      if (index == idx) {
        item.restoreEnrtyDetailDtoList.forEach((childrenItem, childrenIdx) => {
          if (childrenIdx === childrenIndex) {
            childrenItem.delFlag = !childrenItem.delFlag;
          }
        });
      }
    });
    emit('update:list', listRef.value);
  }

  function successHandler(list) {
    const userNames = list.map((item) => item.name).join(',');
    const userIds = list.map((item) => item.userId);

    listRef.value.forEach((item, index) => {
      if (index == currentIndex.value) {
        item.userNames = userNames;
        item.addRecipientIdList = userIds;
      }
    });

    console.log('restoreList', listRef.value);

    emit('update:list', listRef.value);
    closeModal();
  }

  function successConditionHandler(val) {
    listRef.value.forEach((item, index) => {
      if (index == currentIndex.value) {
        item.restoreEnrtyDetailDtoList = item.restoreEnrtyDetailDtoList.map((childrenItem, idx) => {
          if (idx == childrenCurrentIndex.value) {
            const tempItem = { ...childrenItem, ...val, editFlag: true };
            return tempItem;
          } else {
            return childrenItem;
          }
        });
      }
    });

    console.log('listRef.value', listRef.value);
    emit('update:list', listRef.value);
  }

  function successNewConditionHandler(val) {
    console.log('val', val);

    const { activityId, originalID, addRecipientIdList } = val;

    const newEntryFlagArr = listRef.value.filter((item) => item.newEntryFlag);

    console.log('newEntryFlagArr', newEntryFlagArr);

    const sucVal = addRecipientIdList.map((item) => item.userId);
    const userNames = addRecipientIdList.map((item) => item.name).join(',');

    const tempVal = {
      workItemID: props.workItemId,
      newEntryFlag: true,
      ...val,
      userNames,
      addRecipientIdList: sucVal,
    };

    if (newEntryFlagArr.length) {
      let isAlike = false;
      newEntryFlagArr.forEach((item) => {
        if (item.activityId == activityId && item.originalID == originalID) {
          isAlike = true;
          const tempRecipientList = addRecipientIdList.filter(
            (recItem) => !item.addRecipientIdList.includes(recItem.userId),
          );

          const disposeList = tempRecipientList.map((item) => item.userId);
          const disposeUserNames = tempRecipientList.map((item) => item.name).join(',');
          item.addRecipientIdList.push(...disposeList);
          item.userNames = `${item.userNames},${disposeUserNames}`;
        }
      });

      if (!isAlike) {
        listRef.value.push(tempVal);
      }
    } else {
      listRef.value.push(tempVal);
    }

    emit('update:list', listRef.value);
  }

  function openChooseModal(index) {
    currentIndex.value = index;
    openModal(true);
  }

  function openConditionModelHandler(index, childrenIndex, childrenItem) {
    currentIndex.value = index;
    childrenCurrentIndex.value = childrenIndex;

    openConditionModel(true, {
      isUpdate: true,
      record: childrenItem,
    });
  }

  function delStateHandler(index) {
    listRef.value.splice(index, 1);
    emit('update:list', listRef.value);
  }
</script>

<style scoped lang="less">
  .list-main {
    margin: 0 auto;
    flex: 1;
    border-radius: 4px 4px 4px 4px;

    .time {
      color: #999999;
    }

    .item {
      margin-bottom: 20px;
      padding: 0 16px;

      .top-info {
        display: flex;
        justify-content: space-between;
        font-family: PingFang SC-Semibold, PingFang SC;

        .title {
          font-weight: 600;
          color: #333333;
        }
      }
    }

    .item-content {
      padding: 0 16px;
    }

    .children-item {
      width: 100%;
      border-radius: 2px 2px 2px 2px;
      padding: 10px 0;
      border-bottom: 1px solid #f5f6f7;

      .desc {
        font-size: 14px;
        color: #333333;
        flex: 0 0 30%;

        &.del {
          text-decoration: line-through double #ed6f6f;
        }
      }
    }
  }
</style>
